<template>
  <div class="category-edit">
    <el-form :model="$props" :rules="rules" :inline="true" ref="editForm">
      <el-form-item label="类别名称" prop="name">
        <el-input
          :value="name"
          @input="$emit('update:name', $event)"
        ></el-input>
      </el-form-item>
      <el-form-item label="父级类别" prop="parent">
        <el-cascader
          clearable
          :value="parent"
          @input="$emit('update:parent', $event)"
          :options="twoCategory"
          :props="{
            expandTrigger: 'hover',
            label: 'name',
            value: 'id',
            emitPath: false,
            checkStrictly: true,
          }"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="显示顺序">
        <el-input-number
          :min="-999"
          :max="999"
          :value="sort_order"
          @input="$emit('update:sort_order', $event)"
        ></el-input-number>
      </el-form-item>
      <el-row>
        <el-form-item label="上传图片">
          <el-input :value="banner_image_alt"></el-input>
        </el-form-item>
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="banner_image_alt ? [{ url: banner_image_alt }] : []"
          :http-request="uploadImage"
          :on-success="onUploadSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-row>
      <el-row>
        <el-button @click="$emit('clear')">清空</el-button>
        <el-button type="primary" @click="$emit('cancel')">取消</el-button>
        <el-button type="success" @click="onSubmit">确定</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
  name: "CategoryEdit",
  computed: {
    ...mapGetters(["twoCategory", "treeCategory"]),
  },
  props: {
    id: { type: [Number, undefined], default: undefined },
    name: String,
    sort_order: Number,
    parent: { type: [Number, undefined], default: undefined },
    image: { type: Number },
    banner_image_alt: { type: String, default: undefined },
  },
  data() {
    const validateParent = (rule, value, callback) => {
      if (this.id && this.id === this.parent) {
        return callback(new Error("商品类别的父级类别不能是自身"));
      }
      callback();
    };
    return {
      rules: {
        name: [
          { required: true, message: "类别名称为必填项！", trigger: "blur" },
        ],
        parent: [{ validator: validateParent, trigger: "change" }],
      },
    };
  },
  methods: {
    async onSubmit() {
      try {
        await this.$refs.editForm.validate();
        // console.log(this.$props)
        this.$emit("submit", this.$props);
        // this.$refs.editForm.resetFields()
      } catch (e) {
        console.log("新建商品表单验证", e);
      }
    },
    //使用 onUploadSuccess 函数
    // uploadImage({ file }) {
    //   // uploadImage 的参数就是上传的图片的信息
    //   // console.log("file", file);
    //   //生成以formData对象
    //   const fd = new FormData();
    //   fd.append("image", file);
    //
    //   //接收一个 formData作为参数
    //   return this.$api.uploadImage(fd);
    // },
    //不使用 onUploadSuccess 函数
    async uploadImage({ file }) {
      // uploadImage 的参数就是上传的图片的信息
      // console.log("file", file);
      //生成以formData对象
      const fd = new FormData();
      fd.append("image", file);

      //接收一个 formData作为参数
      const { id: imageId, image: url } = await this.$api.uploadImage(fd);
      this.$emit("update:image", imageId);
      this.$emit("update:banner_image_alt", url);
    },
    //文件上传成功时的钩子  获取图片上传时相应的数据
    onUploadSuccess(data) {
      // console.log(data)
      const { id: imageId, image: url } = data;
      // 上传图片成功之后 返回一个图片的ID 和图片的URL 把获取到的id和url保存起来 提交给父组件，父组件再更新 最新的图片数据就填上去了
      this.$emit("update:image", imageId);
      this.$emit("update:banner_image_alt", url);
    },
  },
  watch: {
    id() {
      // 只是清除上次的验证残留在页面上的结果
      this.$refs.editForm.clearValidate();
    },
  },
};
</script>

<style lang="scss" scoped>
.category-edit {
  /*height: 500px;*/
  /*display: flex;*/
  /*justify-content: center;*/
  /*align-items: center;*/
  .el-dialog {
    &__body {
      background-color: violet;
    }
    .el-form {
      width: 90%;
      /*background-color: yellow;*/
      &__type-line {
        display: flex;
        justify-content: space-around;
      }
      &__upload-line {
      }
    }
  }
}
</style>
